package com.bawei.a2010kotlin.viewmodel_livedata

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider


import com.bawei.a2010kotlin.R
import com.bawei.a2010kotlin.databinding.ActivityViewModelBinding
import java.util.*

class ViewModelActivity : AppCompatActivity() {

    private lateinit var  activityViewModelBinding:ActivityViewModelBinding
    private val myViewModel:MyViewModel by viewModels()//惰性初始化，委托
    private var timer:Timer = Timer()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //使用dataBinding注意
        activityViewModelBinding = ActivityViewModelBinding.inflate(layoutInflater)
        setContentView(activityViewModelBinding.root)
        //获得viewmodel
//        myViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
        //点击事件 数字+1
        activityViewModelBinding.bt.setOnClickListener {
            myViewModel.num++
            activityViewModelBinding.tv.text = "当前数字 ${myViewModel.num}"
        }
        //liveData：监听到数据的改变
        myViewModel.numData.observe(this, Observer {
            activityViewModelBinding.tv.text = "当前数字 it"
        })

        //定时器
        timer.schedule(object : TimerTask() {
            override fun run() {
                var num =  myViewModel.numData.value
                myViewModel.numData.postValue(num?.plus(1))//子线程赋值
            }

        },0,1000)



    }



}